package com.mlearning.demo.controller;

import com.alibaba.fastjson.JSONArray;
import com.mlearning.demo.pojo.neo4j.User;
import com.mlearning.demo.service.UserService;
import com.mlearning.demo.util.EncryptUtil;
import com.mlearning.demo.util.JavaMailUtil;
import com.mlearning.demo.util.RandomUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.MimeMessage;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.Date;
import java.util.Properties;

@Controller
public class LogControllor {
    @Autowired
    private UserService userService;

    @RequestMapping("/register")
    public String register(HttpServletRequest request, HttpServletResponse response, Model model) {
        String name;
        String email;
        String passwrod;

        if (request.getParameter("name") != null && request.getParameter("password") != null && request.getParameter("email") != null) {
            name = request.getParameter("name");
            email = request.getParameter("email");
            passwrod = EncryptUtil.getSHA256StrJava(request.getParameter("password"));

            if (userService.creat(name, email, passwrod)) {
                System.out.println("注册成功");
                return "redirect:"+"/login";
            } else {
                //插入失败事件
                model.addAttribute("message", "注册失败！");
                System.out.println("注册失败");
                return "login/register";
            }
        }
        return "login/register";
    }

    @RequestMapping("/checkuseremail")
    public void checkusername(HttpServletRequest req, HttpServletResponse response,@RequestParam("email") String email) throws IOException {
        if(userService.find_email(email)){
            response.getWriter().write( "邮箱已被注册!");
        }else {
            response.getWriter().write("邮箱可用!");
        }
    }

    @RequestMapping("/checkcode")
    public void checkcode(HttpServletRequest req, HttpServletResponse resp,@RequestParam("code") String inputCode) throws IOException {
        // 获取session中的验证码
        String sessionCode = (String) req.getSession().getAttribute("code");
//        System.out.println(sessionCode);

        if(sessionCode != null) {
            //  获取页面提交的验证码
//            System.out.println("页面提交的验证码:" + inputCode);
            if (sessionCode.toLowerCase().equals(inputCode.toLowerCase())) {
                //  验证成功，跳转成功页面
                resp.getWriter().write( "验证成功");
            }else {
                //  验证失败
                resp.getWriter().write( "验证码不正确");
            }
        }else {
            //  验证失败
            resp.getWriter().write( "请点击发送验证码按钮！");
        }
        //  移除session中的验证码
        req.removeAttribute("code");
    }

    @RequestMapping("/login")
    public String login(HttpServletRequest request, HttpServletResponse response,Model model) {
        String email;
        String password;
        HttpSession session = request.getSession();
        session.removeAttribute("user");
//        Cookie cookie = new Cookie("jsessionid", "2jcligmgi6fh");
//        cookie.setMaxAge(Integer.MAX_VALUE);
//        response.addCookie(cookie);

        if (request.getParameter("email") != null && request.getParameter("password") != null) {
//            邮箱地址
            email = request.getParameter("email");
            password = EncryptUtil.getSHA256StrJava(request.getParameter("password"));

            User user = userService.select(email, password);
            if(user != null){
                session.setAttribute("user",user);
                return "redirect:"+"/personal_center";
            }else
            {
                model.addAttribute("message", "用户名/密码错误！");
                System.out.println("登陆失败");
                return "login/login";
            }
        }else {
            return "login/login";
        }
    }

    @RequestMapping("/register_1")
    public String newuser() {
        return "login/register_1";
    }

    @RequestMapping("/SendEmailServlet")
    public void SendEmailServlet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        System.out.println("邮箱发送功能");
        try {
            JavaMailUtil.receiveMailAccount = req.getParameter("email"); // 给用户输入的邮箱发送邮件

            // 1、创建参数配置，用于连接邮箱服务器的参数配置
            Properties props = new Properties();
            // 开启debug调试
            props.setProperty("mail.debug", "true");
            // 发送服务器需要身份验证
            props.setProperty("mail.smtp.auth", "true");
            // 设置右键服务器的主机名
            props.setProperty("mail.host", JavaMailUtil.emailSMTPHost);
            // 发送邮件协议名称
            props.setProperty("mail.transport.protocol", "smtp");

            // 2、根据配置创建会话对象，用于和邮件服务器交互
            Session session = Session.getInstance(props);
            // 设置debug，可以查看详细的发送log
            session.setDebug(true);
            // 3、创建一封邮件
            String code = RandomUtil.getRandom();
//            System.out.println("邮箱验证码：" + code);
            String html = JavaMailUtil.html(code);
            MimeMessage message = JavaMailUtil.creatMimeMessage(session, JavaMailUtil.emailAccount,
                    JavaMailUtil.receiveMailAccount, html);

            // 4、根据session获取邮件传输对象
            Transport transport = session.getTransport();
            // 5、使用邮箱账号和密码连接邮箱服务器emailAccount必须与message中的发件人邮箱一致，否则报错
            transport.connect(JavaMailUtil.emailAccount, JavaMailUtil.emailPassword);
            // 6、发送邮件,发送所有收件人地址
            transport.sendMessage(message, message.getAllRecipients());
            // 7、关闭连接
            transport.close();
            //  写入session
            req.getSession().setAttribute("code", code);
        } catch (Exception e) {
            e.printStackTrace();
            resp.getWriter().write( "发送失败");
        }
    }

    @RequestMapping("/checkpw")
    public void check_pw(HttpServletRequest request,HttpServletResponse response,@RequestParam("password") String password) throws IOException {
        HttpSession session = request.getSession();
        User user = (User) session.getAttribute("user");
        password = EncryptUtil.getSHA256StrJava(password);
        if(userService.select(user.getEmail(), password) != null){
            response.getWriter().write( "true");
        }else
        {
            response.getWriter().write( "false");
        }
    }
}
